package com.peng.leetcode.string;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * IsValid
 * 20. 有效的括号
 * https://leetcode.cn/problems/valid-parentheses/
 *
 * @author: lupeng6
 * @create: 2023/2/24 12:09
 */
public class IsValid {
    public boolean isValid(String s) {
        LinkedList<Character> q = new LinkedList<>();
        Map<Character, Character> pairs = new HashMap<>();
        pairs.put(')', '(');
        pairs.put(']', '[');
        pairs.put('}', '{');

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (pairs.containsKey(c)) {
                if (q.isEmpty() || q.peekLast() != pairs.get(c)) {
                    return false;
                }
                q.pollLast();
            } else {
                q.offerLast(c);
            }
        }
        return q.isEmpty();
    }
}
